//
//  Cookies.m
//  PriceOnline
//
//  Created by Phuong Dinh Le on 2/22/13.
//  Copyright (c) 2013. All rights reserved.
//

#import "Database.h"
#import "Global.h"
#import "UIConstants.h"

@implementation Database

static Database *_database = nil;

- (id)init
{
    self = [super init];
    
    if (self)
    {
#ifdef __SAVE_DB_TO_PLIST__
        _databaseDict = [[NSMutableDictionary alloc] init];
        
        [self load];
#endif        
    }
    
    return self;
}

+ (Database *)sharedInstance
{
    if (_database == nil)
    {
        _database = [[Database alloc] init];
    }
    
    return _database;
}

- (void)load
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:DATABASE_FILE];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:path])
    {
        return;
    }
    
    _databaseDict = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
}

- (BOOL)save
{
#ifdef __SAVE_DB_TO_PLIST__
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:DATABASE_FILE];

    [_databaseDict writeToFile:path atomically:NO];
#endif
    
    return YES;
}

- (id)objectForKey:(NSString *)key
{
#ifdef __SAVE_DB_TO_PLIST__
    return [_databaseDict objectForKey:key];
#else
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
#endif
}

- (void)setObject:(id)value forKey:(NSString *)key
{
#ifdef __SAVE_DB_TO_PLIST__
    [_databaseDict setObject:value forKey:key];
#else
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
#endif
}
@end
